package app

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/xormplus/xorm"
	"github.com/xormplus/xorm/log"
	"os"
	"time"
)

var (
	Engine *xorm.Engine
	DbConn = make(map[string]*xorm.Engine)
)

// db链接
func Db(options ...string) *xorm.Engine {

	var CurrentDbConn string
	if len(options) == 1 && options[0] != "" {
		CurrentDbConn = options[0]
	} else {
		CurrentDbConn = "master"
	}

	key := CurrentDbConn

	if _, ok := DbConn[key]; ok {
		return DbConn[key]
	}

	InitDb(CurrentDbConn)

	return DbConn[key]
}

// @title InitDb
// @description 初始化orm链接
// @auth lucas
// @return
func InitDb(conn string) {
	// 获取配置
	dbConfig, errDbConfig := Config.GetDbConfig(conn)
	fmt.Println(conn)
	if errDbConfig != nil {
		panic(errDbConfig.Error())
	}

	var err error
	Engine, err = xorm.NewEngine("mysql", dbConfig.DbSource)
	if err != nil {
		panic("数据库连接失败---" + err.Error())
	}

	// 设定时区
	location, errTimeZone := time.LoadLocation("Asia/Shanghai")
	if errTimeZone != nil {
		panic("数据库时区设定失败---" + err.Error())
	}

	Engine.TZLocation = location

	// 显示日志到指定目录
	if dbConfig.DbShowSql {
		logConfig, errLogConfig := Config.GetLogConfig("db")
		if errLogConfig != nil {
			panic(errLogConfig.Error())
		}

		Engine.SetLogger(log.NewSimpleLogger(GetDbLogWriter(logConfig.LogFileDir)))
		Engine.ShowSQL(true)
	}

	DbConn[conn] = Engine

	return
}

// 获取日志实例
func GetDbLogWriter(baseDir string) *os.File {
	// 创建目录
	logDir := baseDir + "/sql/"
	if has, _ := PathExist(logDir); !has {
		err := os.MkdirAll(logDir, os.ModePerm)
		if err != nil {
			panic("创建数据库日志目录-" + logDir + "-失败," + err.Error())
		}
	}

	path := logDir + time.Now().Format("2006-01-02") + ".log"
	writer, errPath := os.Create(path)
	if errPath != nil {
		panic("创建数据库日志文件-" + path + "-失败," + errPath.Error())
	}

	return writer
}
